<?php

namespace app\admin\controller\mall;

use app\admin\traits\Curd;
use app\api\model\WeixinUser;
use app\common\controller\AdminController;
use app\common\lib\ArrClass;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\MallGoodsSku;
use app\common\model\MallOrderGoods;
use EasyAdmin\annotation\ControllerAnnotation;
use app\common\model\MallOrder;
use app\common\model\MallUser;
use think\App;
use think\Exception;

/**
 * @ControllerAnnotation(title="申请售后")
 */
class OrderRefund extends AdminController
{
    use Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = (new MallOrder());
        $this->field = "*,openid as wechat,id as get_goods";

    }

    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $where[] = [
                ['status', '=', 4]
            ];
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->field($this->field)
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->with($this->with)
                ->select();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    public function edit($id)
    {
        $row = $this->model->find($id);
        $obj_weixin_user = new WeixinUser();
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            switch ($post['orderToStatus']) {
                case 1: //确认付款
                    $post['status'] = 1;
                    $post['paytime'] = time();
                    break;
                case 2: //确认发货
                    if (!$post['express'] || !$post['expresscom'] || !$post['expresssn']) {
                        $this->error('发货信息请填写完整');
                    }
                    $post['status'] = 2;
                    $post['shipping_time'] = time();
                    break;
                case 3: //确认收货
                    $post['status'] = 3;
                    $post['confirm_time'] = time();
                    break;
                case 4: //退款
                    $post['status'] = 4;
                    $post['refundtime'] = time();
                    $post['isrefund'] = 1;
                    break;
                default:
                    break;
            }
            $goodslist = (new MallOrderGoods())->where("order_id", '=', $id)->select()->toArray();
            $ids = array_column($goodslist, 'option_id');
            $goods_sku = (new MallGoodsSku())->where('id', 'in', $ids)->select()->toArray();
            $sku_lists = [];
            if (!empty($goods_sku)) {
                foreach ($goods_sku as $v) {
                    $sku_lists[$v['id']] = $v;
                }
            }
            $this->model->startTrans();
            try {
                $save = $row->save($post);
                // 发送打印请求
//                if ($post['orderToStatus'] == 1) {
//                    $setting = (new MallSetting())->where("name='isopenid'")->find();
//                    if ($setting && $setting['option_value'] == 1) {
//                        $guid = Str::guid();
//                        $content = "<FS2><center>**#1 荐贝康**</center></FS2>";
//                        $content .= str_repeat('.', 32);
//                        $content .= "<FS2><center>--在线支付--</center></FS2>";
//                        $content .= "<FS><center>荐贝康小程序商城</center></FS>";
//                        $content .= "订单时间:" . $row['create_time'] . "\n";
//                        $content .= "订单编号:" . $row['ordersn'] . "\n";
//                        $content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14);
//                        $content .= "<table>";
//                        $content .= "<tr><td>名称</td><td>数量</td><td>单价</td></tr>";
//                        foreach ($goodslist as $k => $v) {
//
//                            $content .= "<tr><td>" . $v['goods_name'] . "</td><td>x" . $v['total'] . "</td><td>" . $v['price'] . "</td></tr>";
//                        }
//                        $content .= "</table>";
//                        $content .= str_repeat('.', 32);
//                        $content .= "小计:￥" . $row['orderprice'] . "\n";
//                        $content .= "折扣:￥" . $row['discountprice'] . " \n";
//                        $content .= str_repeat('*', 32);
//                        $content .= "订单总价:￥" . $row['payprice'] . " \n";
//                        $content .= str_repeat('*', 32);
//                        $content .= "收货人:" . $row['realname'] . " \n";
//                        $content .= "收货地址:" . $row['address'] . " \n";
//                        $content .= "收货人电话:" . $row['mobile'] . " \n";
//                        $content .= "<FS2><center>**#1 完**</center></FS2>";
//                        $senddata = array(
//                            'machineCode' => '4004701676',
//                            'content' => $content,
//                            'type' => 1,
//                            'id' => $guid
//                        );
//                        Sign::getInstance()->__post($senddata, 'print/printer');
//                    }
//                }
                if ($post['orderToStatus'] == 4) {
                    //执行退款，返回库存
                    if (!empty($goodslist)) {
                        $update_data = [];
                        foreach ($goodslist as $v) {
                            $update_data[] = [
                                "id" => $v['option_id'],
                                "stock" => $sku_lists[$v['option_id']]['stock'] + $v['total'],

                            ];
                        }
                        (new MallGoodsSku())->saveAll($update_data);
                    }
                    //执行退款
                    $order = $row->toArray();
                    $objArr = ArrClass::payAttr();
                    $obj = ArrClass::initClass('wx', $objArr, [], true);
                    $res = $obj->refund($order['ordersn'], $order['ordersn'], $order['payprice'] * 100, $order['payprice'] * 100);
                    if ($res['return_code'] === 'SUCCESS') {
                        if ($res['result_code'] != 'SUCCESS') {
                            throw new Exception("操作失败");
                        }
                    }else{
                        throw new Exception("操作失败");
                    }
                }
                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }

            $this->success('保存成功');
        }
        switch ($row['status']) {
            case 0:
                $row['statusname'] = '待付款';
                break;
            case 1:
                $row['statusname'] = '待发货';
                break;
            case 2:
                $row['statusname'] = '待收货';
                break;
            case 3:
                $row['statusname'] = '已完成';
                break;
            case 4:
                $row['statusname'] = '售后/退款';
                break;
            default:
                $row['statusname'] = '已取消';
                break;
        }
        $userinfo = $obj_weixin_user->getUserByList($row['openid'], 'nickName');
        $row['nickName'] = $userinfo['nickName'];
        $goodslist = (new MallOrderGoods())->getByOrderGoodsList($id);
        //$addinfo =(new MallUserAddress())->where([['id','=',$row['address_id']]])->find();
        $row['cityarea'] = '';
        $this->assign('row', $row);
        $this->assign('goodslist', $goodslist);
        return $this->fetch();
    }
}